package com.tspark.tspark1.controller;

import com.tspark.tspark1.service.UserService;
import com.tspark.tspark1.zoo.constant.MessageConstant;
import com.tspark.tspark1.zoo.pojo.dto.LoginDTO;
import com.tspark.tspark1.zoo.pojo.vo.LoginVO;
import com.tspark.tspark1.zoo.properties.RegexProperties;
import com.tspark.tspark1.zoo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Autowired
    private RegexProperties regexProperties;
    @Autowired
    private UserService userService;


    @PostMapping("/register")
    public Result<LoginVO> register(@RequestBody LoginDTO loginDTO) {
        log.info("用户注册：{}", loginDTO);
        //参数校验:
        //判空
        if (loginDTO == null || loginDTO.getUsername().isEmpty() || loginDTO.getPassword().isEmpty()) {
            return Result.fail(MessageConstant.LOGIN_DTO_EMPTY);
        }
        //是否合法
        if (!loginDTO.getUsername().matches(regexProperties.getUsernameRegex())) {
            return Result.fail(MessageConstant.ILLEGAL_USERNAME);
        }
        if (!loginDTO.getPassword().matches(regexProperties.getPasswordRegex())) {
            return Result.fail(MessageConstant.ILLEGAL_PASSWORD);
        }
        //开始进行注册逻辑
        LoginVO loginVO = userService.register(loginDTO);
        return Result.success(loginVO);
    }

    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录：{}", loginDTO);
        //参数校验:
        //判空
        if (loginDTO == null || loginDTO.getUsername().isEmpty() || loginDTO.getPassword().isEmpty()) {
            return Result.fail(MessageConstant.LOGIN_DTO_EMPTY);
        }
        //开始登录
        LoginVO loginVO = userService.login(loginDTO);
        return Result.success(loginVO);
    }
}
